﻿using CommonEntity.Handlers;
using ScienceAppService.ModuleInterface;
using ScienceAppService.RpcUtils;
using ScienceRpcServe.Protos;
using ImageRecord = CommonEntity.CommonImageEntities.ImageRecord;

namespace ScienceAppService.ModuleService;
public class HistoryImageService : IHistoryImageService
{
    private HistoryImageRecord.HistoryImageRecordClient _rpcClient;

    public event CommonHandler<string>? AlarmEvent;

    public HistoryImageService()
    {
        _rpcClient = RpcConfigure.Instance.GetHistoryImageRecordClient();
    }

    public async Task<List<ImageRecord>> GetImageRecords(int pageIndex, int pageNum)
    {
        try
        {
            var rs = new List<ImageRecord>();
            var records = await _rpcClient.FindImageRecordsAsync(new RecordSearchRequest(){PageIndex = pageIndex, PageNum = pageNum});

            foreach (var rd in records.ImageRecords)
            {
                rs.Add(new ImageRecord()
                {
                    Id = rd.Id,
                    PatientName = rd.PatientName,
                    SeriesDescription = rd.SeriesDescription,
                    CreateTime = Convert.ToDateTime(rd.CreateTime),
                    Dimension = rd.Dimension,
                    Directory = rd.Directory,
                });
            }

            return rs;
        }
        catch (Exception e)
        {
            AlarmEvent?.Invoke("get record fail...");
        }

        return new List<ImageRecord>();
    }

    public async Task DeleteRecord(int Id)
    {
        try
        {
            var rs = await _rpcClient.DeleteImageRecordAsync(new IntRequest(){Value = Id});
            if (!string.IsNullOrEmpty(rs.Remark))
            {
                AlarmEvent?.Invoke(rs.Remark);
            }
        }
        catch (Exception e)
        {
            AlarmEvent?.Invoke("delete record fail...");
        }
    }

    /// <summary>
    /// 获取历史记录总数
    /// </summary>
    /// <returns></returns>
    public async Task<int> GetRecordCount()
    {
        var rs = await _rpcClient.GetImageRecordCountAsync(new EmptyRequest());
        if (!string.IsNullOrEmpty(rs.Remark))
        {
            AlarmEvent?.Invoke(rs.Remark);
            return -1;
        }

        return rs.Value;
    }
}
